import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { Portfolio, PortfolioHolding, Transaction, AssetAllocation, AllocationResult } from '../../types';
import { portfolioAPI } from '../../services/api';

interface PortfolioState {
  portfolios: Portfolio[];
  currentPortfolio: Portfolio | null;
  holdings: PortfolioHolding[];
  transactions: Transaction[];
  allocationResult: AllocationResult | null;
  performance: any;
  riskAnalysis: any;
  loading: boolean;
  error: string | null;
}

const initialState: PortfolioState = {
  portfolios: [],
  currentPortfolio: null,
  holdings: [],
  transactions: [],
  allocationResult: null,
  performance: null,
  riskAnalysis: null,
  loading: false,
  error: null,
};

// 异步actions
export const fetchPortfolios = createAsyncThunk(
  'portfolio/fetchPortfolios',
  async (_, { rejectWithValue }) => {
    try {
      const portfolios = await portfolioAPI.getPortfolios();
      return portfolios;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取投资组合列表失败');
    }
  }
);

export const createPortfolio = createAsyncThunk(
  'portfolio/createPortfolio',
  async (portfolioData: {
    name: string;
    description?: string;
    total_amount: number;
  }, { rejectWithValue }) => {
    try {
      const portfolio = await portfolioAPI.createPortfolio(portfolioData);
      return portfolio;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '创建投资组合失败');
    }
  }
);

export const fetchPortfolio = createAsyncThunk(
  'portfolio/fetchPortfolio',
  async (id: number, { rejectWithValue }) => {
    try {
      const portfolio = await portfolioAPI.getPortfolio(id);
      return portfolio;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取投资组合详情失败');
    }
  }
);

export const updatePortfolio = createAsyncThunk(
  'portfolio/updatePortfolio',
  async ({ id, data }: { id: number; data: Partial<Portfolio> }, { rejectWithValue }) => {
    try {
      const portfolio = await portfolioAPI.updatePortfolio(id, data);
      return portfolio;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '更新投资组合失败');
    }
  }
);

export const deletePortfolio = createAsyncThunk(
  'portfolio/deletePortfolio',
  async (id: number, { rejectWithValue }) => {
    try {
      await portfolioAPI.deletePortfolio(id);
      return id;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '删除投资组合失败');
    }
  }
);

export const fetchHoldings = createAsyncThunk(
  'portfolio/fetchHoldings',
  async (portfolioId: number, { rejectWithValue }) => {
    try {
      const holdings = await portfolioAPI.getHoldings(portfolioId);
      return holdings;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取持仓信息失败');
    }
  }
);

export const fetchTransactions = createAsyncThunk(
  'portfolio/fetchTransactions',
  async (portfolioId: number, { rejectWithValue }) => {
    try {
      const transactions = await portfolioAPI.getTransactions(portfolioId);
      return transactions;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取交易记录失败');
    }
  }
);

export const createTransaction = createAsyncThunk(
  'portfolio/createTransaction',
  async ({ portfolioId, data }: {
    portfolioId: number;
    data: {
      product: number;
      transaction_type: 'buy' | 'sell';
      quantity: number;
      price: number;
    };
  }, { rejectWithValue }) => {
    try {
      const transaction = await portfolioAPI.createTransaction(portfolioId, data);
      return transaction;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '创建交易失败');
    }
  }
);

export const getAssetAllocation = createAsyncThunk(
  'portfolio/getAssetAllocation',
  async (data: AssetAllocation, { rejectWithValue }) => {
    try {
      const result = await portfolioAPI.getAssetAllocation(data);
      return result;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取资产配置建议失败');
    }
  }
);

export const rebalancePortfolio = createAsyncThunk(
  'portfolio/rebalancePortfolio',
  async ({ portfolioId, rebalanceType }: { portfolioId: number; rebalanceType: string }, { rejectWithValue }) => {
    try {
      const result = await portfolioAPI.rebalancePortfolio(portfolioId, rebalanceType);
      return result;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '投资组合再平衡失败');
    }
  }
);

export const fetchPerformance = createAsyncThunk(
  'portfolio/fetchPerformance',
  async ({ portfolioId, days }: { portfolioId: number; days?: number }, { rejectWithValue }) => {
    try {
      const performance = await portfolioAPI.getPerformance(portfolioId, days);
      return performance;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取业绩分析失败');
    }
  }
);

export const fetchRiskAnalysis = createAsyncThunk(
  'portfolio/fetchRiskAnalysis',
  async (portfolioId: number, { rejectWithValue }) => {
    try {
      const riskAnalysis = await portfolioAPI.getRiskAnalysis(portfolioId);
      return riskAnalysis;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || '获取风险分析失败');
    }
  }
);

const portfolioSlice = createSlice({
  name: 'portfolio',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
    setCurrentPortfolio: (state, action: PayloadAction<Portfolio | null>) => {
      state.currentPortfolio = action.payload;
    },
    clearAllocationResult: (state) => {
      state.allocationResult = null;
    },
    clearPerformance: (state) => {
      state.performance = null;
    },
    clearRiskAnalysis: (state) => {
      state.riskAnalysis = null;
    },
  },
  extraReducers: (builder) => {
    // 获取投资组合列表
    builder
      .addCase(fetchPortfolios.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchPortfolios.fulfilled, (state, action: PayloadAction<Portfolio[]>) => {
        state.loading = false;
        // 确保返回的数据是数组
        if (Array.isArray(action.payload)) {
          state.portfolios = action.payload;
        } else {
          console.error('fetchPortfolios返回的数据不是数组:', action.payload);
          state.portfolios = [];
        }
        state.error = null;
      })
      .addCase(fetchPortfolios.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 创建投资组合
    builder
      .addCase(createPortfolio.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(createPortfolio.fulfilled, (state, action: PayloadAction<Portfolio>) => {
        state.loading = false;
        // 确保portfolios是数组后再push
        if (Array.isArray(state.portfolios)) {
          state.portfolios.push(action.payload);
        } else {
          console.error('state.portfolios不是数组，重新初始化:', state.portfolios);
          state.portfolios = [action.payload];
        }
        state.error = null;
      })
      .addCase(createPortfolio.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取投资组合详情
    builder
      .addCase(fetchPortfolio.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchPortfolio.fulfilled, (state, action: PayloadAction<Portfolio>) => {
        state.loading = false;
        state.currentPortfolio = action.payload;
        state.error = null;
      })
      .addCase(fetchPortfolio.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 更新投资组合
    builder
      .addCase(updatePortfolio.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(updatePortfolio.fulfilled, (state, action: PayloadAction<Portfolio>) => {
        state.loading = false;
        const index = state.portfolios.findIndex(p => p.id === action.payload.id);
        if (index !== -1) {
          state.portfolios[index] = action.payload;
        }
        if (state.currentPortfolio?.id === action.payload.id) {
          state.currentPortfolio = action.payload;
        }
        state.error = null;
      })
      .addCase(updatePortfolio.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 删除投资组合
    builder
      .addCase(deletePortfolio.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(deletePortfolio.fulfilled, (state, action: PayloadAction<number>) => {
        state.loading = false;
        state.portfolios = state.portfolios.filter(p => p.id !== action.payload);
        if (state.currentPortfolio?.id === action.payload) {
          state.currentPortfolio = null;
        }
        state.error = null;
      })
      .addCase(deletePortfolio.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取持仓信息
    builder
      .addCase(fetchHoldings.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchHoldings.fulfilled, (state, action: PayloadAction<PortfolioHolding[]>) => {
        state.loading = false;
        state.holdings = action.payload;
        state.error = null;
      })
      .addCase(fetchHoldings.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取交易记录
    builder
      .addCase(fetchTransactions.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchTransactions.fulfilled, (state, action: PayloadAction<Transaction[]>) => {
        state.loading = false;
        state.transactions = action.payload;
        state.error = null;
      })
      .addCase(fetchTransactions.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 创建交易
    builder
      .addCase(createTransaction.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(createTransaction.fulfilled, (state, action: PayloadAction<Transaction>) => {
        state.loading = false;
        state.transactions.unshift(action.payload);
        state.error = null;
      })
      .addCase(createTransaction.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取资产配置建议
    builder
      .addCase(getAssetAllocation.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(getAssetAllocation.fulfilled, (state, action: PayloadAction<AllocationResult>) => {
        state.loading = false;
        state.allocationResult = action.payload;
        state.error = null;
      })
      .addCase(getAssetAllocation.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 投资组合再平衡
    builder
      .addCase(rebalancePortfolio.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(rebalancePortfolio.fulfilled, (state) => {
        state.loading = false;
        state.error = null;
      })
      .addCase(rebalancePortfolio.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取业绩分析
    builder
      .addCase(fetchPerformance.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchPerformance.fulfilled, (state, action) => {
        state.loading = false;
        state.performance = action.payload;
        state.error = null;
      })
      .addCase(fetchPerformance.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });

    // 获取风险分析
    builder
      .addCase(fetchRiskAnalysis.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchRiskAnalysis.fulfilled, (state, action) => {
        state.loading = false;
        state.riskAnalysis = action.payload;
        state.error = null;
      })
      .addCase(fetchRiskAnalysis.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const {
  clearError,
  setCurrentPortfolio,
  clearAllocationResult,
  clearPerformance,
  clearRiskAnalysis,
} = portfolioSlice.actions;

export default portfolioSlice.reducer;